package com.rpc.demo.provider.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author: ZhaoJie
 * @Date: 2022/4/7
 * @Description:
 * @Modify: ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */

public class ProviderNettyServer {

    /**
     *
     */
    private static ChannelInboundHandlerAdapter providerHandler;

    /**
     * @author: zhaojie
     * @date: 2022/4/7
     * @description: 服务端netty开启
     * @method: startServer
     * @param null:
     * @class:  ProviderNettyServer
     * @return: null
     */
    public void startServer(String hostName, int port) {
        startServer0(hostName,port);
    }

    //编写一个方法，完成对NettyServer的初始化和启动

    private static void startServer0(String hostname, int port) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                                      @Override
                                      protected void initChannel(SocketChannel ch) throws Exception {
                                          ChannelPipeline pipeline = ch.pipeline();
                                          pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                                          pipeline.addLast(new ObjectEncoder());
                                          pipeline.addLast(providerHandler); //业务处理器

                                      }
                                  }

                    );

            ChannelFuture channelFuture = serverBootstrap.bind(hostname, port).sync();
            System.out.println("服务提供方开始提供服务~~");
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public ChannelInboundHandlerAdapter getProviderHandler() {
        return providerHandler;
    }

    public void setProviderHandler(ChannelInboundHandlerAdapter providerHandler) {
        this.providerHandler = providerHandler;
    }
}
